using System.Diagnostics;

namespace 高校员工餐饮信息管理系统.Middleware
{
    /// <summary>
    /// 请求日志记录中间件
    /// 记录每次请求的用户ID、时间、接口路径等信息
    /// </summary>
    public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestLoggingMiddleware> _logger;

        public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var stopwatch = Stopwatch.StartNew();
            
            // 记录请求信息
            var requestInfo = new
            {
                Method = context.Request.Method,
                Path = context.Request.Path,
                QueryString = context.Request.QueryString.ToString(),
                UserAgent = context.Request.Headers["User-Agent"].ToString(),
                RemoteIpAddress = context.Connection.RemoteIpAddress?.ToString(),
                UserId = context.User?.Identity?.Name ?? "Anonymous",
                Timestamp = DateTime.Now
            };
            
            _logger.LogInformation(
                "请求开始 => {Method} {Path}{QueryString} | 用户: {UserId} | IP: {RemoteIp} | 时间: {Timestamp:yyyy-MM-dd HH:mm:ss}",
                requestInfo.Method,
                requestInfo.Path,
                requestInfo.QueryString,
                requestInfo.UserId,
                requestInfo.RemoteIpAddress,
                requestInfo.Timestamp
            );

            try
            {
                // 调用下一个中间件
                await _next(context);
            }
            finally
            {
                stopwatch.Stop();
                
                // 记录响应信息
                _logger.LogInformation(
                    "请求结束 => {Method} {Path} | 状态码: {StatusCode} | 耗时: {ElapsedMs}ms",
                    context.Request.Method,
                    context.Request.Path,
                    context.Response.StatusCode,
                    stopwatch.ElapsedMilliseconds
                );
            }
        }
    }
}

